﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GUIEXAM13.Properties;
using Newtonsoft.Json;

namespace GUIEXAM13
{
    public struct SerializableClothing
    {
        public string Id;
        public string Type;
        public string Color;
        public string Picture;
    }

    public class ClothingDataAccess
    {
        private readonly string _filePath = Environment.CurrentDirectory + @"\clothing.json";
       
        public void SaveAllClothing(ObservableCollection<ClothingDomain> clothing)
        {
            var serializableClothing = clothing.Select(clothing_ => new SerializableClothing
                                                                        {
                                                                            Id = clothing_.Id, 
                                                                            Type = clothing_.Type, 
                                                                            Color = clothing_.Color, 
                                                                            Picture = clothing_.Picture
                                                                        }).ToList();

            var streamWriter = new StreamWriter(_filePath, false);
            streamWriter.Write(JsonConvert.SerializeObject(serializableClothing));
            streamWriter.Close();
        }

        public ObservableCollection<ClothingDomain> GetAllClothing()
        {
            if (!File.Exists(_filePath)) return new ObservableCollection<ClothingDomain>();

            var streamReader = new StreamReader(_filePath);
            var deserializedClothing = new List<SerializableClothing>();
            var returnClothingDomainCollection = new ObservableCollection<ClothingDomain>();

            deserializedClothing = JsonConvert.DeserializeObject<List<SerializableClothing>>(streamReader.ReadToEnd());
            streamReader.Close();

            if (deserializedClothing == null) return returnClothingDomainCollection;

            foreach (var deserializedClothing_ in deserializedClothing)
            {
                returnClothingDomainCollection.Add(new ClothingDomain
                                                       {
                                                           Id = deserializedClothing_.Id,
                                                           Type = deserializedClothing_.Type,
                                                           Color = deserializedClothing_.Color,
                                                           Picture = deserializedClothing_.Picture
                                                       });
            }

            return returnClothingDomainCollection;
        }
    }
}
